package com.huaxiafinance.management.controller;

import com.huaxiafinance.management.dto.request.OrgDto;
import com.huaxiafinance.management.model.Org;
import com.huaxiafinance.management.service.OrgUserService;
import com.huaxiafinance.management.util.MessageResult;
import com.huaxiafinance.management.util.ServiceCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller("userOrgController")
@RequestMapping("/userOrg")
public class UserOrgController {

  private static final Logger log = Logger.getLogger(UserOrgController.class);

  @Autowired
  OrgUserService orgUserService;

  @RequestMapping(value = "/newOrg", produces = "application/json; charset=utf-8")
  public @ResponseBody
  String newOrg(OrgDto dto) {
    log.info("新增组织机构请求参数：" + dto);

    MessageResult messageResult = orgUserService.newOrg(dto);

    log.info("新增组织机构返回参数：" + messageResult.getAsJSON());

    return messageResult.getAsJSON();
  }

  @RequestMapping(value = "/queryOrg", produces = "application/json; charset=utf-8")
  public @ResponseBody
  String queryOrg() {
    MessageResult messageResult = new MessageResult();

    List<Org> orgList = orgUserService.queryOrg();

    if (CollectionUtils.isNotEmpty(orgList)) {
      messageResult.setData(orgList);
      messageResult.setResultMessage(ServiceCode.SUCCESS);
    } else {
      messageResult.setResultCode("0001");
      messageResult.setMsg("未新增组织机构！");
    }

    return messageResult.getAsJSON();
  }

  @RequestMapping(value = "/updOrg", produces = "application/json; charset=utf-8")
  public @ResponseBody
  String orgIsEnable(OrgDto dto) {
    log.info("组织机构是否停用请求参数：" + dto);

    MessageResult messageResult = null;

    if (dto.getIsEnable() != null) {
      messageResult = orgUserService.orgIsEnable(dto);
    } else {
      messageResult = orgUserService.updOrg(dto);
    }

    log.info("组织机构启/停用返回参数：" + messageResult.getAsJSON());

    return messageResult.getAsJSON();
  }
}
